<template>
  <template v-if="showFlag">
    <a-tooltip>
      <template #title>{{ content }}</template>
      <div :id="id" class="overflow-tooltip" :style="{ maxWidth: isNumber(maxWidth) ? maxWidth + 'px' : maxWidth }">
        {{ content }}
      </div>
    </a-tooltip>
  </template>
  <template v-else>
    <div :id="id" class="overflow-tooltip" :style="{ maxWidth: isNumber(maxWidth) ? maxWidth + 'px' : maxWidth }">
      {{ content }}
    </div>
  </template>
</template>
<script lang="ts" setup>
import { toRefs, ref, onMounted, onBeforeUnmount } from 'vue'
const props = defineProps<{
  content: any
  maxWidth?: number | string
}>()

const { content, maxWidth } = toRefs(props)
const id = Math.random().toString(36).slice(2)
const showFlag = ref(false)

const init = () => {
  const el: HTMLElement = document.getElementById(id) as HTMLElement
  if (!el) {
    return
  }
  const elComputed = document.defaultView?.getComputedStyle(el, '')
  const padding = elComputed
    ? parseInt(elComputed.paddingLeft.replace('px', '')) + parseInt(elComputed.paddingRight.replace('px', ''))
    : 0

  const range = document.createRange()
  range.setStart(el, 0)
  range.setEnd(el, el.childNodes.length)
  const rangeWidth = range.getBoundingClientRect().width

  if (rangeWidth + padding > el.offsetWidth || el.scrollWidth > el.offsetWidth) {
    showFlag.value = true
  } else {
    showFlag.value = false
  }
}

const isNumber = (val) => {
  return typeof val === 'number'
}

onMounted(() => {
  init()
  window.addEventListener('resize', init)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', init)
})
</script>
<style lang="less" scoped>
.overflow-tooltip {
  display: inline-block;
  width: 100%;
  // max-width: calc(100% - 29px);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: 1;
  vertical-align: middle;
}
.overflow-tooltip:empty:before {
  content: '--';
}
</style>
